﻿using System.Collections.Generic;
using System.Globalization;
using Orchard.ContentManagement;
using Orchard.ContentManagement.MetaData;
using Orchard.ContentManagement.MetaData.Builders;
using Orchard.ContentManagement.MetaData.Models;
using Orchard.ContentManagement.ViewModels;

namespace Orchard.CounterField.Settings {
    public class CounterFieldListModeEvents : ContentDefinitionEditorEventsBase {

        public override IEnumerable<TemplateViewModel> PartFieldEditor(ContentPartFieldDefinition definition) {
            if (definition.FieldDefinition.Name == "CounterField") {
                var model = definition.Settings.GetModel<CounterFieldSettings>();
                yield return DefinitionTemplate(model);
            }
        }

        public override IEnumerable<TemplateViewModel> PartFieldEditorUpdate(ContentPartFieldDefinitionBuilder builder, IUpdateModel updateModel) {
            if (builder.FieldType != "CounterField") {
                yield break;
            }

            var model = new CounterFieldSettings();
            if (updateModel.TryUpdateModel(model, "CounterFieldSettings", null, null)) {
                //builder.WithSetting("CounterFieldSettings.Type", model.Type.ToString());
                builder.WithSetting("CounterFieldSettings.Hint", model.Hint);
                builder.WithSetting("CounterFieldSettings.Required", model.Required.ToString());
                builder.WithSetting("CounterFieldSettings.Format", model.Format);
                builder.WithSetting("CounterFieldSettings.Interval", model.Interval.ToString(CultureInfo.InvariantCulture));
            }

            yield return DefinitionTemplate(model);
        }
    }
}